/*!
 * Jodit Editor (https://xdsoft.net/jodit/)
 * License https://xdsoft.net/jodit/license.html
 * Copyright 2013-2018 Valeriy Chupurnov https://xdsoft.net
 */

import {Jodit} from '../Jodit';
import {Config} from "../Config";
import {css} from '../modules/Helpers';
import {Widget} from "../modules/Widget";
import {Dom} from "../modules/Dom";
import {ControlType, ToolbarButton} from "../modules/ToolbarCollection";


Config.prototype.controls.code = <ControlType>{
    tagRegExp: /^(pre)$/i,
    tags: ["pre"],
    css: {
        // "font-weight": ["code", "700"]
    },
    isActive: (editor: Jodit, btn: ControlType, button: ToolbarButton): boolean => {
        const current: Node|false = editor.selection.current();

        if (current) {
            const currentBpx: HTMLElement = <HTMLElement>Dom.closest(current, Dom.isBlock, editor.editor);
            return currentBpx &&
                currentBpx !== editor.editor && currentBpx.nodeName !== 'undefined' && currentBpx.nodeName.toLowerCase() === 'pre'
        }

        return false;
    },
    tooltip: "Code",
};



/**
 * code plugin
 */
export function code(editor: Jodit) {
    const callBack: Function = (command: string): false | void => {
        const control: ControlType = <ControlType>Jodit.defaultOptions.controls[command];
        const cssOptions: {[key: string]: string|string[]}|{[key: string]: (editor: Jodit, value: string) => boolean} = {...control.css},
            cssRules: {[key: string]: string} = {};

        Object.keys(cssOptions).forEach((key: string) => {
            cssRules[key] = Array.isArray(cssOptions[key]) ?  (<any>cssOptions[key])[0] : cssOptions[key];
        });

        editor.selection.applyCSS(
            cssRules,
            control.tags ? control.tags[0] : undefined,
            <any>control.css
        );

        editor.setEditorValue();
        return false;
    };

    editor.registerCommand('code', {
        exec: callBack,
        // hotkeys: 'ctrl+'
    });
}